#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <memory.h>
using namespace std;

struct node {
    int w, v;
    node(int v, int w) {
        this->w = w;
        this->v = v;
    }
};
  
bool vis[10005];
queue<int> q;
vector<node> G[10005];
int tx[10005], d[10005];
int n, m;
int u, v, a, b;
int ans;

bool spfa() {
    memset(d, 0x3f, sizeof(d));
    d[0] = 0;
    q.push(0);
    tx[0] = 1;
    vis[0] = 1;
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        vis[u] = 0;
        for(unsigned i = 0; i < G[u].size(); ++i) {
            int v = G[u][i].v;
            int dis = G[u][i].w;
            if (d[v] > d[u] + dis) {
                d[v] = d[u] + dis;
                if (!vis[v]) {
                	if (++tx[v] > n) {
        	            return 0;
            	    }
                    q.push(v);
                    vis[v] = 1;
                }
            }
        }
    }
    for (int i = 0; i < n; ++i) {
    	if (tx[i] <= 0) return 0;
	}
    return 1;
}

void calc() {
    for (int i = 0; i < n; ++i) {
        if (d[i] > d[ans]) ans = i;
    }
}

int main() {
    bool flag;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; ++i) {
        scanf("%d %d %d %d", &u, &v, &a, &b);
        flag = 1;
        for (int j = 0; j < G[v].size(); ++j) {
            if (G[v][j].v == u) {
                flag = 0;
                if (G[v][j].w > -a) {
                    G[v][j].w = -a;
                }
                break;
            }
        }
        if (flag) {
        	G[v].push_back(node(u, -a));
		}
        flag = 1;
        for (int j = 0; j < G[u].size(); ++j) {
            if (G[u][j].v == u) {
                flag = 0;
                if (G[u][j].w > b) {
                    G[u][j].w = b;
                }
				break;
            }
        }
        if (flag)  {
        	G[u].push_back(node(v, b));
		}
    }
    
    if (spfa()) {
        calc();
        printf("%d\n", d[ans] - d[0]);
    } else {
        printf("-1");
    }
    
    return 0;
}
